package com.xsystem.util;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;

public final class StringUtil {

	private StringUtil() {
	}

	public static String findNonDigitChars(String str) {
		if (str == null) {
			return null;
		}

		final Pattern p = Pattern.compile("[^0-9]");
		final Matcher m = p.matcher(str);

		boolean found = m.find();
		if (!found) {
			return null;
		} else {
			return m.group();
		}
	}

	public static boolean containsOnlyNumbers(String st) {

		if (st == null || st.length() == 0) {
			return false;
		}

		String str = (st.startsWith("+")) ? st.substring(1) : st;
		for (int i = 0; i < str.length(); i++) {

			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}

		return true;
	}

	public static String stripOffPlusSign(String mobileNumber) {
		return mobileNumber.replaceAll("\\+", "");
	}

	public static String trimCharsOffString(String str, String charsToTrim) {

		if (str == null) {
			return null;
		}

		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < str.length(); i++) {
			String s = str.substring(i, i + 1);

			if (!charsToTrim.contains(s)) {
				sb.append(s);
			}
		}

		String resultStr = sb.toString();

		if (resultStr.equals("")) {
			return null;
		}

		return resultStr;
	}

	public static String generateRandomNumericString(int length) {
		StringBuilder sb = new StringBuilder();

		while (length > 0) {
			char ch = (char) rand('0', '9');
			if (Character.isDigit(ch)) {
				sb.append(ch);
				length--;
			}
		}
		return sb.toString();
	}

	public static String generateRandomAlphaNumericString(int length) {
		StringBuilder sb = new StringBuilder();

		while (length > 0) {
			char ch = (char) rand('0', 'z');
			if (Character.isLetterOrDigit(ch)) {
				sb.append(ch);
				length--;
			}
		}
		return sb.toString();
	}

	public static int rand(int lo, int hi) {
		int n = hi - lo + 1;
		Random rn = new Random();
		int i = rn.nextInt() % n;
		if (i < 0) {
			i = -i;
		}
		return lo + i;
	}

	public static boolean isEmpty(String str) {
		return str == null || str.trim().isEmpty();
	}

	public static Map<String, String> parseNvp(final String inputString) {
		if (inputString == null || inputString.trim().equals("")) {
			return new HashMap<String, String>();
		}

		final Map<String, String> hm = new HashMap<String, String>();

		final StringTokenizer st = new StringTokenizer(inputString, "&;");

		while (st.hasMoreTokens()) {
			final String s = st.nextToken();
			final String[] nvp = s.split("=", 2);
			try {
				hm.put(nvp[0], URLDecoder.decode(String.valueOf(nvp[1]), "UTF-8"));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return hm;
	}

	public static String convertToProperUCS(final String ucsString) throws NumberFormatException {
		StringBuilder sb = new StringBuilder();
		if (ucsString.isEmpty() || ucsString.length() < 4) {
			throw new NumberFormatException();
		}
		for (int i = 0; i < ucsString.length(); i = i + 4) {
			final String s = ucsString.substring(i, i + 4);
			sb.append((char) Integer.parseInt(s, 16));
		}
		return sb.toString();
	}

	public static String convertListToCsv(List<String> list) {
		StringBuilder sb = new StringBuilder();
		for (String s : list) {
			if (sb.length() != 0) {
				sb.append(','); // separator
			}
			if (s != null) {
				sb.append("\"" + s.replace("\"", "\"\"") + "\""); // escape and enclose
			}
		}
		return sb.toString();
	}

	public static Map<String, String> convertStringToMap(String output) {
		if (output == null || output.trim().equals("")) {
			return new HashMap<String, String>();
		}

		final Map<String, String> hm = new HashMap<String, String>();

		final StringTokenizer st = new StringTokenizer(output, "&;");

		while (st.hasMoreTokens()) {
			final String s = st.nextToken();
			if (s.indexOf("=") != -1) {
				final String[] nvp = s.split("=", 2);
				try {
					hm.put(nvp[0].trim(), URLDecoder.decode(String.valueOf(nvp[1]), "UTF-8").trim());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return hm;
	}

	public static String capitalizeFirstChar(final String target) {
		return Character.toUpperCase(target.charAt(0)) + target.substring(1);
	}

	public static String lowerFirstChar(final String target) {
		return Character.toLowerCase(target.charAt(0)) + target.substring(1);
	}

	public static String replaceParameters(String template, Map<String, String> parameters) {
		String message = template;
		if (message != null && parameters != null) {
			for (Map.Entry<String, String> entry : parameters.entrySet()) {
				if (entry.getValue() != null) {
					message = message.replace("#{" + entry.getKey() + "}", entry.getValue());
				}
			}
		}
		return message;
	}

	public static JSONArray toJSONArray(String commaDelimitedString) {
		JSONArray jsonArray = new JSONArray();
		String[] stringArray = commaDelimitedString.split(",");
		for (String entry : stringArray) {
			jsonArray.add(entry);
		}

		return jsonArray;

	}

	public static String toCommaDelimitedString(JSONArray jsonArray) {
		Object[] stringArray = jsonArray.toArray();
		StringBuffer output = new StringBuffer("");

		for (Object entry : stringArray) {
			output.append(entry.toString());
			output.append(',');
		}

		if (output.toString().endsWith(",")) {
			return output.toString().substring(0, output.toString().length() - 1);
		}
		return output.toString();
	}
}
